package com.kkshop.model;

import java.util.Set;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

@Entity
@Table(name = "categories")
public class Category implements Persistent<Long> {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "parent_id")
    private Category parent;
    
    @OneToMany(fetch = FetchType.EAGER)
    @JoinColumn(name = "parent_id")
    private Set<Category> children;
    
    @Basic
    @Column(nullable = false, length = 50)
    private String name;
    
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Category getParent() {
        return parent;
    }

    public void setParent(Category parent) {
        this.parent = parent;
    }

    public Set<Category> getChildren() {
        return children;
    }

    public void setChildren(Set<Category> children) {
        this.children = children;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public boolean hasParent() {
        return parent != null;
    }
    
    public boolean hasChildren() {
        return children.size() > 0;
    }

    public boolean equals(Object other) {
        if(!(other instanceof Category)) {
            return false;
        }
        
        Category that = (Category) other;
        
        
        
        return new EqualsBuilder()
                .append(id, that.id)
                .append(name, that.name).isEquals();
    }

    public int hashCode() {
        return new HashCodeBuilder()
                .append(id)
                .append(name).toHashCode();
    }

    public String toString() {
        return new ToStringBuilder(this)
                .append(id)
                .append(name).toString();
    }
}
